package aip.core.dao.typeHandler;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.support.lob.LobCreator;
import org.springframework.jdbc.support.lob.LobHandler;
import org.springframework.orm.ibatis.support.AbstractLobTypeHandler;

public class BlobInputStreamTypeHandler extends AbstractLobTypeHandler
{

    /**
     * Constructor used by iBATIS: fetches config-time LobHandler from
     * SqlMapClientFactoryBean.
     * @see org.springframework.orm.ibatis.SqlMapClientFactoryBean#getConfigTimeLobHandler
     */
    public BlobInputStreamTypeHandler()
    {
        super();
    }

    /**
     * Constructor used for testing: takes an explicit LobHandler.
     */
    protected BlobInputStreamTypeHandler(LobHandler lobHandler)
    {
        super(lobHandler);
    }

    protected void setParameterInternal(PreparedStatement ps, int index,
            Object value, String jdbcType, LobCreator lobCreator)
            throws SQLException, IOException
    {
        if (value != null)
        {
            InputStream is = (InputStream) value;
            lobCreator.setBlobAsBinaryStream(ps, index, is, is.available());
        }
        else
        {
            lobCreator.setBlobAsBytes(ps, index, null);
        }
    }

    protected Object getResultInternal(ResultSet rs, int index,
            LobHandler lobHandler) throws SQLException, IOException
    {
        Blob blob = rs.getBlob(index);
        return blob;
        // InputStream is = lobHandler.getBlobAsBinaryStream(rs, index);
        //
        // if (is != null)
        // {
        // ObjectInputStream ois = new ObjectInputStream(is);
        // try
        // {
        // return ois.readObject();
        // }
        // catch (ClassNotFoundException ex)
        // {
        // throw new SQLException("Could not deserialize BLOB contents: "
        // + ex.getMessage());
        // }
        // finally
        // {
        // ois.close();
        // }
        // }
        // else
        // {
        // return null;
        // }
    }

    public Object valueOf(String s)
    {
        return s;
    }

}
